<template>
  <div class="statistics-container">
    <!-- 销售趋势图表 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>销售趋势</span>
              <el-radio-group v-model="salesTimeRange" size="small" @change="handleTimeRangeChange">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" v-loading="loading">
            <div ref="salesChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 商品销量排行和销售分类占比图表 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>商品销量排行</span>
            </div>
          </template>
          <div class="chart-container" v-loading="loading">
            <div ref="productRankChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>销售分类占比</span>
            </div>
          </template>
          <div class="chart-container" v-loading="loading">
            <div ref="categorySalesChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 销售明细表格 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>销售明细</span>
              <el-button size="small" @click="exportData">导出数据</el-button>
            </div>
          </template>
          <el-table :data="statisticsData.salesDetail" style="width: 100%" border v-loading="loading">
            <el-table-column prop="date" label="日期" width="180" />
            <el-table-column prop="orderCount" label="订单数" width="120" />
            <el-table-column prop="salesAmount" label="销售额" width="150">
              <template #default="scope">
                ¥{{ scope.row.salesAmount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="productCount" label="商品数量" width="120" />
            <el-table-column prop="customerCount" label="客户数" width="120" />
            <el-table-column prop="avgOrderAmount" label="平均客单价" width="150">
              <template #default="scope">
                ¥{{ scope.row.avgOrderAmount.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="(size: number) => { pageSize = size; fetchStatisticsData(); }"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { getStatistics } from '@/api/merchant'
import * as echarts from 'echarts'

// 加载状态
const loading = ref(false)

// 销售时间范围
const salesTimeRange = ref('month')

// 图表引用
const salesChartRef = ref<HTMLElement | null>(null)
const productRankChartRef = ref<HTMLElement | null>(null)
const categorySalesChartRef = ref<HTMLElement | null>(null)
let salesChart: echarts.ECharts | null = null
let productRankChart: echarts.ECharts | null = null
let categorySalesChart: echarts.ECharts | null = null

// 统计数据
const statisticsData = reactive({
  salesTrend: [] as any[],
  productRank: [] as any[],
  categorySales: [] as any[],
  salesDetail: [] as any[]
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取销售数据
const fetchStatisticsData = async () => {
  loading.value = true
  try {
    const response = await getStatistics({
      timeRange: salesTimeRange.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })

    if (response.data.code === 200) {
      // 更新统计数据
      Object.assign(statisticsData, response.data.data)

      // 更新分页数据
      if (response.data.data.salesDetail) {
        total.value = response.data.data.total || 0
      }

      // 渲染图表
      renderCharts()
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 处理时间范围变化
const handleTimeRangeChange = () => {
  fetchStatisticsData()
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchStatisticsData()
}

// 导出数据
const exportData = () => {
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '导出中...' })

  setTimeout(() => {
    loadingInstance.close()
    ElMessage.success('数据导出成功')
  }, 1500)
}

// 渲染图表
const renderCharts = () => {
  nextTick(() => {
    // 销售趋势图表
    if (salesChartRef.value) {
      if (!salesChart) {
        salesChart = echarts.init(salesChartRef.value)
      }

      const salesOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['销售额', '订单数']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: statisticsData.salesTrend.map(item => item.date)
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            axisLabel: {
              formatter: '{value} 元'
            }
          },
          {
            type: 'value',
            name: '订单数',
            axisLabel: {
              formatter: '{value} 单'
            }
          }
        ],
        series: [
          {
            name: '销售额',
            type: 'bar',
            data: statisticsData.salesTrend.map(item => item.salesAmount)
          },
          {
            name: '订单数',
            type: 'line',
            yAxisIndex: 1,
            data: statisticsData.salesTrend.map(item => item.orderCount)
          }
        ]
      }

      salesChart.setOption(salesOption)
    }

    // 商品销量排行图表
    if (productRankChartRef.value) {
      if (!productRankChart) {
        productRankChart = echarts.init(productRankChartRef.value)
      }

      const productRankOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: statisticsData.productRank.map(item => item.name)
        },
        series: [
          {
            name: '销量',
            type: 'bar',
            data: statisticsData.productRank.map(item => item.sales)
          }
        ]
      }

      productRankChart.setOption(productRankOption)
    }

    // 销售分类占比图表
    if (categorySalesChartRef.value) {
      if (!categorySalesChart) {
        categorySalesChart = echarts.init(categorySalesChartRef.value)
      }

      const categorySalesOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: statisticsData.categorySales.map(item => item.name)
        },
        series: [
          {
            name: '销售额',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: statisticsData.categorySales.map(item => ({
              value: item.amount,
              name: item.name
            }))
          }
        ]
      }

      categorySalesChart.setOption(categorySalesOption)
    }
  })
}

// 监听销售时间范围变化
watch(salesTimeRange, () => {
  handleTimeRangeChange()
})

// 页面加载时获取数据
onMounted(() => {
  // 模拟数据
  statisticsData.salesTrend = [
    { date: '2023-05-01', salesAmount: 12500.50, orderCount: 120 },
    { date: '2023-05-02', salesAmount: 14200.75, orderCount: 135 },
    { date: '2023-05-03', salesAmount: 15300.25, orderCount: 142 },
    { date: '2023-05-04', salesAmount: 13800.50, orderCount: 128 },
    { date: '2023-05-05', salesAmount: 16200.00, orderCount: 150 },
    { date: '2023-05-06', salesAmount: 15800.25, orderCount: 145 },
    { date: '2023-05-07', salesAmount: 17500.75, orderCount: 160 }
  ]

  statisticsData.productRank = [
    { name: '商品A', sales: 320 },
    { name: '商品B', sales: 280 },
    { name: '商品C', sales: 250 },
    { name: '商品D', sales: 220 },
    { name: '商品E', sales: 190 }
  ]

  statisticsData.categorySales = [
    { name: '电子产品', amount: 45000 },
    { name: '服装', amount: 32000 },
    { name: '食品', amount: 28000 },
    { name: '家居', amount: 20000 },
    { name: '其他', amount: 15000 }
  ]

  statisticsData.salesDetail = [
    {
      date: '2023-05-01',
      orderCount: 120,
      salesAmount: 12500.50,
      productCount: 350,
      customerCount: 110,
      avgOrderAmount: 104.17
    },
    {
      date: '2023-05-02',
      orderCount: 135,
      salesAmount: 14200.75,
      productCount: 380,
      customerCount: 125,
      avgOrderAmount: 105.19
    },
    {
      date: '2023-05-03',
      orderCount: 142,
      salesAmount: 15300.25,
      productCount: 410,
      customerCount: 130,
      avgOrderAmount: 107.75
    },
    {
      date: '2023-05-04',
      orderCount: 128,
      salesAmount: 13800.50,
      productCount: 360,
      customerCount: 118,
      avgOrderAmount: 107.82
    },
    {
      date: '2023-05-05',
      orderCount: 150,
      salesAmount: 16200.00,
      productCount: 430,
      customerCount: 140,
      avgOrderAmount: 108.00
    }
  ]

  total.value = 100

  // 渲染图表
  renderCharts()

  // 监听窗口大小变化，重新渲染图表
  window.addEventListener('resize', () => {
    salesChart?.resize()
    productRankChart?.resize()
    categorySalesChart?.resize()
  })

  // 实际项目中应该调用API获取数据
  // fetchStatisticsData()
})
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
